package com.server.llh.llhserverwork.activity.my;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseNFCActivity;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.UserDataInfoBean;
import com.server.llh.llhserverwork.receiver.GetCardBroadCast;
import com.server.llh.llhserverwork.utils.Constant;
import com.server.llh.llhserverwork.utils.Md5;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.ToastTool;
import com.server.llh.llhserverwork.utils.ToastUtil;
import com.server.llh.llhserverwork.view.CustomerKeyboards;
import com.server.llh.llhserverwork.view.PasswordEditText;
import com.server.llh.llhserverwork.view.dialog.CommonDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by ZTF on 2017-06-08.
 */

public class PayTaskActivity extends LlhBaseNFCActivity implements
        CustomerKeyboards.CustomerKeyboardClickListener,
        PasswordEditText.PasswordFullListener {
    private static final String TAG = "PayTask";
    @BindView(R.id.titleName)
    TextView titleName;
    @BindView(R.id.main_back)
    ImageButton mainBack;
    @BindView(R.id.leftBtn_RL_title_base)
    RelativeLayout leftBtnRLTitleBase;
    @BindView(R.id.serverName)
    TextView serverName;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.inputdaidou)
    EditText inputdaidou;
    @BindView(R.id.inputserverm)
    EditText inputserverm;
    @BindView(R.id.layout1)
    LinearLayout layout1;
    @BindView(R.id.pay_button)
    Button payButton;
    @BindView(R.id.layout3)
    RelativeLayout layout3;
    @BindView(R.id.client_card)
    TextView clientCard;
    @BindView(R.id.client_name)
    TextView clientName;
    @BindView(R.id.client_money)
    TextView clientMoney;
    @BindView(R.id.client_m)
    LinearLayout clientM;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.phone_view)
    LinearLayout phoneView;
    @BindView(R.id.client_address)
    TextView clientAddress;
    @BindView(R.id.address_show)
    LinearLayout addressShow;
    @BindView(R.id.userInfo)
    LinearLayout userInfo;
    @BindView(R.id.loginDialogViewSwitcher)
    LinearLayout loginDialogViewSwitcher;
    @BindView(R.id.login_scrollview)
    ScrollView loginScrollview;
    @BindView(R.id.logindialog_space)
    RelativeLayout logindialogSpace;
    String serTransId, transStatus, subCateId, customerId, serSignRecordId,
            supplierTypeId, supplierId;
    String payable, serverPay, pocketPay, client_card_num;
    String orgId, orgType, userId, orgName, token;
    private GetCardBroadCast getCardBroad = null;
    private CustomerKeyboards mCustomerKeyboard;
    private PasswordEditText mPasswordEt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        titleName.setText("代购支付");
        Intent intent = getIntent();
        if (intent != null) {
            serTransId = intent.getStringExtra("serTransId");
            transStatus = intent.getStringExtra("transStatus");
            subCateId = intent.getStringExtra("subCateId");
            customerId = intent.getStringExtra("customerId");
            serSignRecordId = intent.getStringExtra("serSignRecordId");
        }
        token = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getApplicationContext());
        supplierTypeId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE, getApplicationContext());
        supplierId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID, getApplicationContext());
        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,
                getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID,
                getApplicationContext());
        orgType = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE,
                getApplicationContext());
        orgName = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_NAME,
                getApplicationContext());

    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == -1000) {
                String cardId = String.valueOf(msg.obj);
                getUserInfo(cardId, "");
                return;
            }
        }
    };
    private String userName;
    List<UserDataInfoBean.DataBean.AccountListBean> accountListBeen = new ArrayList<>();

    //    MyMoneyAdapter myMoneyAdapter=null;
    private void getUserInfo(String myCardId, String token) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("icNumber", myCardId);
        lRequest.addParam("token", token);
        lRequest.addParam("needAcc", 1);
        lRequest.setUri(ServerPort.GET_CARD_INFO);
        lRequest.setUriType(UrlsTools.LLH_DATA_APP);
        lRequest.setType(String.class);

        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null) {
                    accountListBeen.clear();
                    Log.d(TAG, "dataBean ==" + responseBean.toString());
                    UserDataInfoBean userDataInfoBean = new Gson().fromJson(responseBean, UserDataInfoBean.class);
                    userName = userDataInfoBean.getData().getUserName();
                    userId = userDataInfoBean.getData().getUserId();
                    if (TextUtils.isEmpty(userName) || "".equals(userName)) {
                        ToastUtil.showToast(getApplicationContext(), "抱歉,该卡没有用户信息...");
                        return;
                    }
//                    if (!TextUtils.isEmpty(userName)) {
//                        et_cardNo.setText(userName);
//                        itemType = true;
//                        if ( userDataInfoBean.getData().getAccountList()!=null){
//                            accountListBeen=  userDataInfoBean.getData().getAccountList();
//                            myMoneyAdapter=new MyMoneyAdapter(getApplicationContext(),accountListBeen);
//                            et_userName.setAdapter(myMoneyAdapter);
//                        }
//                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.READ_CARDACTION);
        getCardBroad = new GetCardBroadCast();
        getCardBroad.setmHandler(mHandler);

        getLbm().registerReceiver(getCardBroad, filter);

        super.onResume();
    }


    @OnClick({R.id.main_back, R.id.pay_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_back:
                onBackPressed();
                break;
            case R.id.pay_button:
                payable = inputdaidou.getText().toString();
                serverPay = inputserverm.getText().toString();
                client_card_num = clientCard.getText().toString();
                if (TextUtils.isEmpty(payable) && TextUtils.isEmpty(serverPay)) {
                    ToastTool.showText(getApplicationContext(), "数据不能为空!");
                } else if (TextUtils.isEmpty(client_card_num)
                        || "".equals(client_card_num)) {
                    ToastTool.showText(getApplicationContext(), "请刷卡支付!");
                } else {
                    if ("".equals(serverPay) || "".equals(payable)) {
                        serverPay = "0";
                        payable = "0";
                        double pocketPayD = Double.parseDouble(payable)
                                + Double.parseDouble(serverPay);
                        if (pocketPayD >= Double.parseDouble("300")) {
                            ToastTool.showText(getApplicationContext(), "需要用户输入密码");
                            setPwdView();
                        } else {
                            payTask("", payable, serverPay, serTransId,
                                    transStatus, subCateId, customerId,
                                    serSignRecordId);
                        }
                    }
                }
                break;
        }
    }

    private void payTask(String pwd, String purchasePrice, String servicePrice,
                         String serTransId, String transStatus, String subCateId,
                         String customerId, String serSignRecordId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", token);
        lRequest.addParam("serTransId", serTransId);
        lRequest.addParam("serTransStatus", transStatus);
        lRequest.addParam("purchasePrice", purchasePrice);
        lRequest.addParam("servicePrice", servicePrice);
        lRequest.addParam("waitersId", SharedPreferenceUtil.getUserInfo("newUserId", getApplicationContext()));
        lRequest.addParam("customerId", customerId);
        lRequest.addParam("serSignRecordId", serSignRecordId);
        lRequest.addParam("supplierType", supplierTypeId);
        lRequest.addParam("supplierId", supplierId);
        lRequest.addParam("isHasField", "0");
        lRequest.addParam("pwd", Md5.md5s(Md5.md5s(pwd)));
        lRequest.setUri(ServerPort.GET_CARD_INFO);
        lRequest.setUriType(UrlsTools.LLH_DATA_APP);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null) {
                    Log.d(TAG, "responseBean==" + responseBean);
                }
            }
        });
    }

    private ImageView delete_dialog;
    CommonDialog.Builder builder = null;

    private void setPwdView() {
        final CommonDialog.Builder builder = new CommonDialog.Builder(this);
        builder.setView(R.layout.dialog_customer_keyboard).fromBottom()
                .fullWidth().create().show();
        mPasswordEt = builder.getView(R.id.password_edit_text);
        delete_dialog = builder.getView(R.id.delete_dialog);
        mCustomerKeyboard = builder.getView(R.id.custom_key_board);
        mCustomerKeyboard.setOnCustomerKeyboardClickListener(this);
        mPasswordEt.setEnabled(false);
        mPasswordEt.setOnPasswordFullListener(this);

        delete_dialog.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
    }

    @Override
    public void passwordFull(String password) {
        payable = inputdaidou.getText().toString();
        serverPay = inputserverm.getText().toString();
        System.out.println("password===" + password);
        payTask(password, payable, serverPay, serTransId, transStatus,
                subCateId, customerId, serSignRecordId);
    }

    @Override
    public void click(String number) {
        mPasswordEt.addPassword(number);
    }

    @Override
    public void delete() {
        mPasswordEt.deleteLastPassword();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (getCardBroad != null)
            getLbm().unregisterReceiver(getCardBroad);
    }

    @Override
    public void showProgress() {
        try {
            showProgress(PayTaskActivity.this);
        } catch (Exception e) {

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception E) {

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.activity_pay_task;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }

}
